import React, { useMemo, useEffect, useState, useCallback } from 'react';
import { Select, Tag, Tooltip, Space, Spin, Badge, Button, message, notification, Drawer, List } from 'antd';
import {
  RobotOutlined,
  ThunderboltOutlined,
  DollarOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  WarningOutlined,
  DownOutlined
} from '@ant-design/icons';
import { ModelType, MODEL_INFO } from '@/types/models';
import modelDiscoveryService, { AvailableModel } from '@/services/model-discovery.service';
import ModelStatusIndicator from '../ModelStatusIndicator';
import { useModelDiscoveryStore } from '@/stores/model-discovery.store';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import './style.css';

interface ModelSelectorProps {
  value?: string;
  onChange?: (model: string) => void;
  disabled?: boolean;
  showStatus?: boolean;
  className?: string;
  useDynamicModels?: boolean; // 是否使用动态模型数据
  autoSwitch?: boolean; // 模型故障时自动切换
  showNotifications?: boolean; // 显示模型状态通知
}

const ModelSelector: React.FC<ModelSelectorProps> = ({
  value,
  onChange,
  disabled = false,
  showStatus = true,
  className = '',
  useDynamicModels = true, // 默认使用动态模型
  autoSwitch = true, // 默认开启自动切换
  showNotifications = true // 默认显示通知
}) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';
  const [sheetVisible, setSheetVisible] = useState(false);
  const [availableModels, setAvailableModels] = useState<AvailableModel[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);
  const [previousStatuses, setPreviousStatuses] = useState<Record<string, string>>({});
  const { updateModelStatus, refreshModels } = useModelDiscoveryStore();
  
  // 订阅模型更新和状态变化
  useEffect(() => {
    if (useDynamicModels) {
      setLoading(true);
      const unsubscribe = modelDiscoveryService.subscribeToModelUpdates((models) => {
        // 检测状态变化并处理通知
        models.forEach(model => {
          const prevStatus = previousStatuses[model.id];
          if (prevStatus && prevStatus !== model.status) {
            handleModelStatusChange(model, prevStatus);
          }
        });
        
        // 更新状态记录
        const newStatuses: Record<string, string> = {};
        models.forEach(m => {
          newStatuses[m.id] = m.status;
        });
        setPreviousStatuses(newStatuses);
        
        setAvailableModels(models);
        setLastRefresh(new Date());
        setLoading(false);
      });
      
      return () => {
        unsubscribe();
      };
    }
  }, [useDynamicModels, previousStatuses]);
  
  // 处理模型状态变化
  const handleModelStatusChange = useCallback((model: AvailableModel, prevStatus: string) => {
    // 模型恢复可用
    if (prevStatus === 'unavailable' && model.status === 'available') {
      if (showNotifications) {
        notification.success({
          message: '模型已恢复',
          description: `${model.displayName} 现在可以使用了`,
          icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
          duration: 4
        });
      }
    }
    
    // 模型变为不可用
    if (prevStatus === 'available' && model.status === 'unavailable') {
      if (showNotifications) {
        notification.warning({
          message: '模型不可用',
          description: `${model.displayName} 当前无法使用`,
          icon: <WarningOutlined style={{ color: '#faad14' }} />,
          duration: 4
        });
      }
      
      // 如果当前选中的模型不可用，自动切换
      if (autoSwitch && value === model.id) {
        handleAutoSwitch();
      }
    }
    
    // 模型降级
    if (model.status === 'available' && model.responseTime && model.responseTime > 5000) {
      if (showNotifications) {
        notification.info({
          message: '模型响应缓慢',
          description: `${model.displayName} 响应时间较长（${model.responseTime}ms）`,
          icon: <ClockCircleOutlined style={{ color: '#1890ff' }} />,
          duration: 3
        });
      }
    }
  }, [value, autoSwitch, showNotifications]);
  
  // 自动切换到可用模型
  const handleAutoSwitch = useCallback(() => {
    const availableModel = availableModels.find(m => 
      m.status === 'available' && m.id !== value
    );
    
    if (availableModel && onChange) {
      onChange(availableModel.id);
      message.info(`已自动切换到 ${availableModel.displayName}`);
    } else {
      message.warning('没有其他可用的模型');
    }
  }, [availableModels, value, onChange]);
  
  // 手动刷新模型列表
  const handleRefresh = useCallback(async () => {
    setLoading(true);
    try {
      await modelDiscoveryService.refreshCache();
      await refreshModels();
      message.success('模型列表已更新');
    } catch (error) {
      message.error('刷新失败');
    } finally {
      setLoading(false);
    }
  }, [refreshModels]);
  
  // 检查模型切换前的可用性
  const handleModelChange = useCallback(async (modelId: string) => {
    const model = availableModels.find(m => m.id === modelId);
    
    if (!model) {
      message.error('选择的模型不存在');
      return;
    }
    
    // 如果模型状态未知，先检查
    if (model.status === 'unknown' || model.status === 'checking') {
      message.loading('正在检查模型可用性...');
      const health = await modelDiscoveryService.checkModelHealth(modelId);
      
      if (health.status !== 'available') {
        message.error('模型当前不可用，请选择其他模型');
        return;
      }
    }
    
    // 警告降级模型
    if (model.status === 'available' && model.responseTime && model.responseTime > 3000) {
      message.warning(`${model.displayName} 响应较慢，可能影响使用体验`);
    }
    
    if (onChange) {
      onChange(modelId);
    }
  }, [availableModels, onChange]);
  
  // 获取模型状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'available':
        return '#52c41a';
      case 'unavailable':
        return '#f5222d';
      case 'checking':
        return '#faad14';
      default:
        return '#d9d9d9';
    }
  };
  
  // 获取提供商标签颜色
  const getProviderColor = (provider: string) => {
    const colors: Record<string, string> = {
      openai: 'green',
      anthropic: 'purple',
      claude: 'purple',
      deepseek: 'blue',
      google: 'cyan',
      meta: 'orange'
    };
    return colors[provider.toLowerCase()] || 'default';
  };
  
  const modelOptions = useMemo(() => {
    if (useDynamicModels && availableModels.length > 0) {
      // 使用动态模型数据
      return availableModels.map(model => ({
        value: model.id,
        label: (
          <div className="model-option">
            <Space>
              <RobotOutlined />
              <span className="model-name">{model.displayName}</span>
              <Tag color={getProviderColor(model.provider)} className="model-provider">
                {model.providerName}
              </Tag>
              {showStatus && (
                <ModelStatusIndicator
                  modelId={model.id}
                  showDetails={false}
                  size="small"
                />
              )}
              {model.recommended && (
                <Tag color="gold">推荐</Tag>
              )}
              {model.responseTime && model.responseTime < 500 && (
                <ThunderboltOutlined style={{ color: '#52c41a' }} title="快速响应" />
              )}
            </Space>
          </div>
        ),
        disabled: model.status !== 'available',
        description: model.errorMessage || `最大 ${model.capabilities.maxTokens} tokens`,
        maxTokens: model.capabilities.maxTokens,
        responseTime: model.responseTime
      }));
    } else {
      // 后备：使用静态模型数据
      return Object.values(MODEL_INFO).map(model => ({
        value: model.id,
        label: (
          <div className="model-option">
            <Space>
              <RobotOutlined />
              <span className="model-name">{model.name}</span>
              <Tag color={model.provider === 'OpenAI' ? 'green' : 'blue'} className="model-provider">
                {model.provider}
              </Tag>
              {showStatus && (
                model.available ? 
                  <CheckCircleOutlined style={{ color: '#52c41a' }} /> :
                  <CloseCircleOutlined style={{ color: '#f5222d' }} />
              )}
            </Space>
          </div>
        ),
        disabled: !model.available,
        description: model.description,
        maxTokens: model.maxTokens,
        costPerToken: model.costPerToken
      }));
    }
  }, [showStatus, availableModels, useDynamicModels]);

  const handleChange = (modelId: string) => {
    if (onChange) {
      onChange(modelId);
    }
  };
  
  const handleRefresh = async () => {
    setLoading(true);
    await modelDiscoveryService.refreshCache();
    setLoading(false);
  };

  const selectedModel = useDynamicModels
    ? availableModels.find(m => m.id === value)
    : MODEL_INFO[value as ModelType];

  // 移动端：底部Sheet菜单
  if (isMobile) {
    const currentModel = useDynamicModels
      ? availableModels.find(m => m.id === value)
      : MODEL_INFO[value as ModelType];

    return (
      <div className={`model-selector-container mobile ${className}`}>
        <Button
          type="text"
          onClick={() => setSheetVisible(true)}
          disabled={disabled}
          className="model-selector-trigger"
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
            minHeight: '44px',
            padding: '8px 12px'
          }}
        >
          <RobotOutlined />
          <span className="text-mobile-sm">
            {currentModel
              ? (useDynamicModels && 'displayName' in currentModel ? currentModel.displayName : currentModel.name)
              : '选择模型'
            }
          </span>
          <DownOutlined style={{ fontSize: '10px' }} />
        </Button>

        <Drawer
          placement="bottom"
          open={sheetVisible}
          onClose={() => setSheetVisible(false)}
          height="auto"
          className="model-selector-sheet"
          styles={{ body: { padding: 0 } }}
          closable={false}
        >
          <div className="model-sheet-header">
            <h3 className="text-mobile-lg" style={{ margin: 0, padding: '16px', fontWeight: 600 }}>
              选择模型
            </h3>
            {useDynamicModels && lastRefresh && (
              <div style={{ padding: '0 16px 12px', borderBottom: '1px solid #f0f0f0' }}>
                <Space>
                  <span style={{ fontSize: '12px', color: '#999' }}>
                    上次刷新: {lastRefresh.toLocaleTimeString()}
                  </span>
                  <Button
                    type="link"
                    size="small"
                    onClick={handleRefresh}
                    loading={loading}
                    icon={<SyncOutlined />}
                  >
                    刷新
                  </Button>
                </Space>
              </div>
            )}
          </div>

          <List
            dataSource={useDynamicModels ? availableModels : Object.values(MODEL_INFO)}
            loading={loading}
            renderItem={(model: any) => {
              const modelId = model.id;
              const isSelected = value === modelId;
              const isAvailable = useDynamicModels
                ? model.status === 'available'
                : model.available;

              return (
                <List.Item
                  onClick={() => {
                    if (isAvailable) {
                      handleModelChange(modelId);
                      setSheetVisible(false);
                    }
                  }}
                  className={`model-sheet-item ${isSelected ? 'selected' : ''} ${!isAvailable ? 'disabled' : ''}`}
                  style={{
                    minHeight: '56px',
                    cursor: isAvailable ? 'pointer' : 'not-allowed',
                    padding: '12px 16px',
                    backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
                    opacity: isAvailable ? 1 : 0.5
                  }}
                >
                  <List.Item.Meta
                    avatar={<RobotOutlined style={{ fontSize: '20px' }} />}
                    title={
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                        <span className="text-mobile-base" style={{ fontWeight: 500 }}>
                          {useDynamicModels ? model.displayName : model.name}
                        </span>
                        {isSelected && <CheckCircleOutlined style={{ color: '#1890ff' }} />}
                        {useDynamicModels && model.recommended && (
                          <Tag color="gold" style={{ margin: 0 }}>推荐</Tag>
                        )}
                        {useDynamicModels && model.responseTime && model.responseTime < 500 && (
                          <ThunderboltOutlined style={{ color: '#52c41a' }} title="快速响应" />
                        )}
                      </div>
                    }
                    description={
                      <div style={{ marginTop: '4px' }}>
                        <Space size="small" wrap>
                          <Tag color={getProviderColor(useDynamicModels ? model.provider : model.provider)}>
                            {useDynamicModels ? model.providerName : model.provider}
                          </Tag>
                          <span className="text-mobile-sm" style={{ color: '#666' }}>
                            最大 {useDynamicModels ? model.capabilities.maxTokens : model.maxTokens} tokens
                          </span>
                          {useDynamicModels && model.responseTime && (
                            <span className="text-mobile-sm" style={{ color: '#999' }}>
                              {model.responseTime}ms
                            </span>
                          )}
                          {useDynamicModels && showStatus && (
                            <Badge
                              status={model.status === 'available' ? 'success' : 'error'}
                              text={model.status === 'available' ? '在线' : '离线'}
                            />
                          )}
                        </Space>
                      </div>
                    }
                  />
                </List.Item>
              );
            }}
          />

          {useDynamicModels && (
            <div className="model-sheet-footer" style={{
              padding: '12px 16px',
              borderTop: '1px solid #f0f0f0',
              background: '#fafafa'
            }}>
              <Space>
                <Badge status="success" text={`${availableModels.filter(m => m.status === 'available').length} 在线`} />
                <Badge status="error" text={`${availableModels.filter(m => m.status !== 'available').length} 离线`} />
              </Space>
            </div>
          )}
        </Drawer>
      </div>
    );
  }

  // 桌面端：保持原有Select组件
  return (
    <div className={`model-selector-container ${className}`}>
      <Space.Compact style={{ width: '100%' }}>
        <Select
          className="model-selector"
          value={value}
          onChange={handleChange}
          disabled={disabled}
          loading={loading}
          style={{ width: '100%', minWidth: 200 }}
          placeholder="选择模型"
          optionLabelProp="label"
          options={modelOptions}
          notFoundContent={loading ? <Spin size="small" /> : "暂无可用模型"}
          dropdownRender={(menu) => (
            <div className="model-dropdown">
              {useDynamicModels && lastRefresh && (
                <div className="model-dropdown-header">
                  <Space>
                    <span style={{ fontSize: '12px', color: '#999' }}>
                      上次刷新: {lastRefresh.toLocaleTimeString()}
                    </span>
                    <a onClick={handleRefresh} style={{ fontSize: '12px' }}>
                      <SyncOutlined spin={loading} /> 刷新
                    </a>
                  </Space>
                </div>
              )}
              {menu}
              <div className="model-dropdown-footer">
                <Space>
                  <Tooltip title="模型速度">
                    <ThunderboltOutlined />
                  </Tooltip>
                  {!useDynamicModels && (
                    <Tooltip title="使用成本">
                      <DollarOutlined />
                    </Tooltip>
                  )}
                  {useDynamicModels && (
                    <Tooltip title="在线状态">
                      <Badge status="success" text={`${availableModels.filter(m => m.status === 'available').length} 在线`} />
                    </Tooltip>
                  )}
                </Space>
              </div>
            </div>
          )}
          optionRender={(option) => (
            <Tooltip
              title={option.data.description}
              placement="right"
            >
              <div className="model-option-item">
                {option.label}
                <div className="model-meta">
                  <span className="model-tokens">最大 {option.data.maxTokens} tokens</span>
                  {option.data.responseTime && (
                    <span className="model-response-time">{option.data.responseTime}ms</span>
                  )}
                  {option.data.costPerToken && (
                    <span className="model-cost">￥{option.data.costPerToken}/token</span>
                  )}
                </div>
              </div>
            </Tooltip>
          )}
        />
      </Space.Compact>

      {selectedModel && useDynamicModels && 'status' in selectedModel && selectedModel.status !== 'available' && (
        <div className="model-warning" style={{ marginTop: '8px' }}>
          <Space>
            <ExclamationCircleOutlined style={{ color: '#faad14' }} />
            <span style={{ color: '#faad14', fontSize: '12px' }}>
              {selectedModel.errorMessage || '该模型当前不可用'}
            </span>
          </Space>
        </div>
      )}

      {selectedModel && !useDynamicModels && 'available' in selectedModel && !selectedModel.available && (
        <div className="model-info">
          <Tooltip title={selectedModel.description}>
            <Tag color="default">{selectedModel.description}</Tag>
          </Tooltip>
        </div>
      )}
    </div>
  );
};

export default ModelSelector;